﻿/*
COPYRIGHT (C) 2009 EPISERVER AB

THIS FILE IS PART OF DYNAMIC CONTENT CONTRIB FOR EPISERVER CMS.
DYNAMIC CONTENT CONTRIB FOR EPISERVER CMS IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

DYNAMIC CONTENT CONTRIB FOR EPISERVER CMS IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH DYNAMIC CONTENT CONTRIB FOR EPISERVER CMS. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Configuration;
using EPiServer.PlugIn;
using EPiServer.Configuration;
using EPiServer.DataAbstraction;
using System.Reflection;
using EPiServer.Core;
using EPiServer.DynamicContent;
using System.Web.UI.WebControls;
using System.Linq;

namespace EPiServer.Research.DynamicContent
{
    [GuiPlugIn(RequireLicenseForLoad=false)]
    public class DCProperties
    {
        [PlugInProperty(Description = "Import Property Types as Dynamic Content", AdminControl = typeof(CheckBox), AdminControlValue = "Checked")]
        public bool ImportPropertyTypes { get; set; }
    }

    public class DCPlugin : PlugInAttribute
    {
        public string Url { get; set; }



        public static void Start()
        {
            DCProperties obj = new DCProperties();

            PlugInSettings.AutoPopulate(obj);
            //Add all properties:
            if (obj.ImportPropertyTypes)
            {
                foreach (PageDefinitionType pdf in PageDefinitionType.List())
                {
                    //We now have a property type
                    try
                    {

                        PropertyData pd = (pdf.TypeName == null) ?
                            PropertyData.CreatePropertyDataObject(pdf.DataType)
                            :
                            PropertyData.CreatePropertyDataObject(pdf.AssemblyName, pdf.TypeName);


                        Type basetype = typeof(PropertyDC<>);
                        Type result = basetype.MakeGenericType(pd.GetType());
                        AddNewDC("[Property] " + pdf.Name, result, pdf.TypeName);
                    }
                    catch
                    {
                        continue;
                    }
                }
            }


            //Find Dynamic Content plugins
            PlugInDescriptor[] plugs=PlugInLocator.Search(new DCPlugin());
            
            foreach (PlugInDescriptor pd in plugs)
            {
                string name = pd.GetAttribute(typeof(DCPlugin)).DisplayName;
                Type tp = pd.PlugInType;
                string description = pd.GetAttribute(typeof(DCPlugin)).Description;

                if(pd.PlugInType.IsSubclassOf(typeof(System.Web.UI.Control))){
                    //We have a user control, handle that
                    Type basetype = typeof(ControlDC<>);
                    tp = basetype.MakeGenericType(tp);
                }

                AddNewDC(name, tp, description);
            }/*
            var typesWithMyAttribute =   from a in AppDomain.CurrentDomain.GetAssemblies()
                                         from t in a.GetTypes()
                                         let attributes = t.GetCustomAttributes(typeof(DCPlugin), true)
                                         where attributes != null && attributes.Length > 0
                                         select t;
            foreach (Type t in typesWithMyAttribute)
            {
                DCPlugin plg = (DCPlugin) t.GetCustomAttributes(typeof(DCPlugin), true)[0];
                Type tp = t;
                if (t.IsSubclassOf(typeof(System.Web.UI.Control)))
                {
                    Type basetype = typeof(ControlDC<>);
                    tp = basetype.MakeGenericType(tp);
                }
                AddNewDC(plg.DisplayName, tp, plg.Description);
            }*/
        }

        public override bool Match(object obj)
        {
            return obj is DCPlugin;
        }


        private static void AddNewDC(string name, Type tp, string description)
        {
            if (DynamicContentFactory.Instance.NameToTypeMap.ContainsKey(name)) return;

            //Add to DynamicContent Factory maps
            EPiServer.DynamicContent.DynamicContentFactory.Instance.NameToTypeMap.Add(name, tp);
            EPiServer.DynamicContent.DynamicContentFactory.Instance.TypeToNameMap.Add(tp, name);

            //Add to config
            ProviderSettings ps = new ProviderSettings(name, tp.AssemblyQualifiedName);
            ps.Parameters.Add("description", description);
            EPiServerSection.Instance.DynamicContentSettings.Controls.Add(ps);
        }
    }
}

